import { postData } from './postData'

export function userHook(formBase?: any) {
  // 如果没有传入 formBase，则获取 postData 中的数据
  const _formBase = formBase || postData().formBase
  // 确保初始有3行数据
  const initializeRows = () => {
    while (_formBase.value.teacher.length < 3) {
      _formBase.value.teacher.push({
        name: '',
        education: '',
        title: '',
        department: '',
        remarks: '',
      })
    }
  }
  // 检查某一行是否已完整填写（姓名、学历、职称都必须填写）
  const isRowCompleted = (row: any) => {
    return row && row.name && row.name.trim() !== '' && row.education !== '' && row.title !== ''
  }

  // 检查某一行是否为空行（所有字段都为空）
  const isRowEmpty = (row: any) => {
    return (
      !row ||
      ((!row.name || row.name.trim() === '') &&
        (!row.education || row.education === '') &&
        (!row.title || row.title === '') &&
        (!row.department || row.department === '') &&
        (!row.remarks || row.remarks === ''))
    )
  }

  // 统计实际填满的数据行数
  const getCompletedRowsCount = () => {
    return _formBase.value.teacher.filter((row) => isRowCompleted(row)).length
  }

  // 检查是否需要添加新行：只有当用户完整填写最后一行时才添加
  const checkAndAddRow = () => {
    const totalRows = _formBase.value.teacher.length
    const lastRow = _formBase.value.teacher[totalRows - 1]

    // 只有当最后一行完整填写（姓名、学历、职称都必须填写）时，才添加新行
    if (lastRow && isRowCompleted(lastRow)) {
      _formBase.value.teacher.push({
        name: '',
        education: '',
        title: '',
        department: '',
        remarks: '',
      })
    }
  }

  // 删除空行（保持最少3行）
  const removeEmptyRows = () => {
    if (_formBase.value.teacher.length <= 3) return

    for (let i = _formBase.value.teacher.length - 1; i >= 0; i--) {
      if (isRowEmpty(_formBase.value.teacher[i]) && _formBase.value.teacher.length > 3) {
        _formBase.value.teacher.splice(i, 1)
      }
    }
  }

  // 确保最少3行
  const ensureMinimumRows = () => {
    while (_formBase.value.teacher.length < 3) {
      _formBase.value.teacher.push({
        name: '',
        education: '',
        title: '',
        department: '',
        remarks: '',
      })
    }
  }

  // 处理输入框失焦：删除空行 + 检查是否需要添加行
  const handleInputBlur = (index: number) => {
    setTimeout(() => {
      // 先删除空行
      removeEmptyRows()
      // 再确保最少3行
      ensureMinimumRows()
      // 最后检查是否需要添加行
      const row = _formBase.value.teacher[index]
      if (row && row.name && row.name.trim() !== '') {
        checkAndAddRow()
      }
    }, 200)
  }

  // 处理选择框变化：检查是否需要添加行
  const handleSelectChange = (index: number) => {
    setTimeout(() => {
      // 选择学历/职称后，检查是否需要添加行
      checkAndAddRow()
    }, 100)
  }

  // 获取字段错误信息：姓名填写后，学历职称必须填写
  const getFieldError = (row: any, index: number, field: string) => {
    if (!row || !row.name || row.name.trim() === '') return ''

    if (field === 'education' && (!row.education || row.education === '')) {
      return '请选择学历/学位'
    }
    if (field === 'title' && (!row.title || row.title === '')) {
      return '请选择职称'
    }
    return ''
  }

  // 获取行的验证状态
  const getRowValidationClass = ({ row }: { row: any }) => {
    if (!row) return ''
    if (row.name && row.name.trim() !== '' && (!row.education || !row.title)) {
      return 'row-incomplete'
    }
    return ''
  }

  return {
    initializeRows,
    isRowCompleted,
    isRowEmpty,
    getCompletedRowsCount,
    ensureMinimumRows,
    handleInputBlur,
    handleSelectChange,
    getFieldError,
    getRowValidationClass,
  }
}
